<template>
  <div class="pro-table">
    <!-- 工具栏 -->
    <div class="pro-table-toolbar" v-if="showToolbar">
      <div class="toolbar-left">
        <slot name="toolbar-left">
          <a-space>
            <a-button 
              v-if="showRefresh" 
              type="text" 
              :icon="h(ReloadOutlined)" 
              @click="handleRefresh"
            >
              刷新
            </a-button>
            <a-button 
              v-if="showDensity" 
              type="text" 
              :icon="h(ColumnHeightOutlined)"
            >
              <a-dropdown>
                <template #overlay>
                  <a-menu @click="handleDensityChange">
                    <a-menu-item key="large">默认</a-menu-item>
                    <a-menu-item key="middle">中等</a-menu-item>
                    <a-menu-item key="small">紧凑</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-button>
            <a-button 
              v-if="showColumnSetting" 
              type="text" 
              :icon="h(SettingOutlined)"
              @click="showColumnModal = true"
            >
              列设置
            </a-button>
          </a-space>
        </slot>
      </div>
      <div class="toolbar-right">
        <slot name="toolbar-right">
          <a-space>
            <a-input-search
              v-if="showSearch"
              v-model:value="searchValue"
              placeholder="搜索..."
              style="width: 200px"
              @search="handleSearch"
            />
          </a-space>
        </slot>
      </div>
    </div>

    <!-- 表格 -->
    <a-table
      v-bind="tableProps"
      :columns="visibleColumns"
      :data-source="dataSource"
      :loading="loading"
      :size="tableSize"
      :scroll="scroll"
      :pagination="paginationConfig"
      @change="handleTableChange"
    >
      <!-- 动态插槽 -->
      <template v-for="(_, name) in $slots" #[name]="slotData">
        <slot :name="name" v-bind="slotData" />
      </template>
    </a-table>

    <!-- 列设置弹窗 -->
    <a-modal
      v-model:open="showColumnModal"
      title="列设置"
      :width="400"
      @ok="handleColumnSettingOk"
    >
      <a-checkbox-group v-model:value="selectedColumns" class="column-setting-group">
        <div v-for="column in allColumns" :key="column.key" class="column-setting-item">
          <a-checkbox :value="column.key">
            {{ column.title }}
          </a-checkbox>
        </div>
      </a-checkbox-group>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, h } from 'vue'
import type { TableProps, TableColumnType } from 'ant-design-vue'
import {
  ReloadOutlined,
  ColumnHeightOutlined,
  SettingOutlined
} from '@ant-design/icons-vue'

interface ProTableColumn extends TableColumnType {
  key: string
  title: string
  hideInTable?: boolean
  hideInSearch?: boolean
}

interface ProTableProps extends Omit<TableProps, 'columns'> {
  columns: ProTableColumn[]
  showToolbar?: boolean
  showRefresh?: boolean
  showDensity?: boolean
  showColumnSetting?: boolean
  showSearch?: boolean
  request?: (params: any) => Promise<{ data: any[]; total: number }>
}

const props = withDefaults(defineProps<ProTableProps>(), {
  showToolbar: true,
  showRefresh: true,
  showDensity: true,
  showColumnSetting: true,
  showSearch: true,
})

const emit = defineEmits<{
  refresh: []
  search: [value: string]
  change: [pagination: any, filters: any, sorter: any]
}>()

// 响应式数据
const loading = ref(false)
const searchValue = ref('')
const tableSize = ref<'large' | 'middle' | 'small'>('middle')
const showColumnModal = ref(false)
const selectedColumns = ref<string[]>([])
const allColumns = ref<ProTableColumn[]>([])

// 初始化列配置
watch(() => props.columns, (newColumns) => {
  allColumns.value = newColumns
  selectedColumns.value = newColumns
    .filter(col => !col.hideInTable)
    .map(col => col.key)
}, { immediate: true })

// 计算属性
const visibleColumns = computed(() => {
  return allColumns.value.filter(col => 
    selectedColumns.value.includes(col.key)
  )
})

const tableProps = computed(() => {
  const { columns, showToolbar, showRefresh, showDensity, showColumnSetting, showSearch, request, ...rest } = props
  return rest
})

const paginationConfig = computed(() => {
  if (props.pagination === false) return false
  
  return {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => 
      `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
    ...props.pagination
  }
})

// 方法
const handleRefresh = () => {
  emit('refresh')
  if (props.request) {
    loadData()
  }
}

const handleSearch = (value: string) => {
  emit('search', value)
}

const handleDensityChange = ({ key }: { key: string }) => {
  tableSize.value = key as 'large' | 'middle' | 'small'
}

const handleTableChange = (pagination: any, filters: any, sorter: any) => {
  emit('change', pagination, filters, sorter)
}

const handleColumnSettingOk = () => {
  showColumnModal.value = false
  // 保存列设置到本地存储
  const storageKey = `pro-table-columns-${props.rowKey || 'default'}`
  localStorage.setItem(storageKey, JSON.stringify(selectedColumns.value))
}

const loadData = async () => {
  if (!props.request) return
  
  loading.value = true
  try {
    const result = await props.request({
      search: searchValue.value,
      // 其他参数...
    })
    // 处理数据...
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化时加载列设置
const initColumnSettings = () => {
  const storageKey = `pro-table-columns-${props.rowKey || 'default'}`
  const savedColumns = localStorage.getItem(storageKey)
  if (savedColumns) {
    try {
      selectedColumns.value = JSON.parse(savedColumns)
    } catch (error) {
      console.error('解析列设置失败:', error)
    }
  }
}

// 暴露方法
defineExpose({
  refresh: handleRefresh,
  reload: loadData,
})

// 初始化
initColumnSettings()
</script>

<style scoped>
.pro-table {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
}

.pro-table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
}

.column-setting-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.column-setting-item {
  padding: 4px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pro-table-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }
}
</style>